<template>
  <div>
    <div>
      <a-upload
        ref="uploadRef"
        :key="uploadKey"
        multiple
        :file-list="fileList"
        :limit="9"
        :action="uploadFile"
        :headers="{ token: accessToken }"
        :show-file-list="false"
        :onSuccess="success"
        :onError="handleError"
        @exceed-limit="handleExceedLimit"
        :data="dataList"
        @before-upload="beforeUpload"
        @change="handleUploadChange"
      >
        <template #upload-button>
          <a-space>
            <a-button type="primary">上传文件</a-button>
          </a-space>
        </template>
      </a-upload>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import uploadFile from '@/api/common';
  import { Message } from '@arco-design/web-vue';
  import {
    handleSuccess,
    handleError,
    beforeUpload,
    accessToken,
  } from '@/components/upload-pic/upload';

  const props = defineProps(['tablePageRef', 'dataList']);
  const emit = defineEmits<{
    (e: 'onSuccess', val: any): void;
  }>();

  const uploadRef = ref(null);
const fileList = ref([]);
  const uploadKey = ref(new Date().getTime());

  function success(res: any) {
    handleSuccess(res);
    props.tablePageRef ? props.tablePageRef.init() : '';
    emit('onSuccess', res);
}

  function handleExceedLimit() {
    Message.warning('最多只能上传9张图片');
}

function handleUploadChange(fileList: any) {

  // 图片全部上传完成重置上传组件
  if (fileList.every(file => file.status === 'done')) {
    fileList.value = [];
    uploadKey.value = new Date().getTime()
  }
}
</script>

<style lang="less" scoped></style>
